package com.isunland.managesystem.ui;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.TaskListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.ExtraValueContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.Task;
import com.isunland.managesystem.entity.TaskLab;
import com.isunland.managesystem.entity.TaskList;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;

public class TaskListFragment extends BaseListFragment {
  protected static final String TAG = "TaskListFragment";
  public static final String EXTRA_MENU_ID = "com.isunland.managesystem.Fragment.MENU_ID";
  public static final int MY_TODO_LIST = 0;// 待办事宜
  public static final int MY_DONE_LIST = 1;// 已办事宜
  public static final int MY_REQUEST = 2;// 我的请求
  public static final int MY_COMPLETED = 3;// 我的办结
  public static final int REQUEST_QUERY = 4;//查询

  //判断是批量同意还是批量驳回
  private static final int AGREE = 0;
  private static final int DISAGREE = 1;
  private ArrayList<Task> mTasks;
  private ArrayList<Task> tasks;
  private int mCurrentPage;
  private boolean isRefresh;
  private boolean isBat = false;//是否批量操作，同意，驳回

  private int mMenuId;
  private TaskListAdapter adapter;
  private Menu mMenu;
  //初始化查询条件
  private String mtypeCode = "";//流程分类code
  private String mtypeName = "";//流程分类name
  private String mifApproveCode = "1";//是否完成审批code
  private String mifApproveName = "否";//是否完成审批name
  private String mapplyName = "";//申请人或部门名
  private String mtitle = "";//标题
  private String mBeginTime = "";//开始时间
  private String mEndTime = "";//结束时间

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    setTitle(mMenuId);
    mTasks = TaskLab.get(getActivity()).getTasks();
    mPullRefreshListView.setMode(Mode.BOTH);
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mMenuId = getArguments().getInt(EXTRA_MENU_ID);
    mCurrentPage = 1;
    setHasOptionsMenu(true);
    setRetainInstance(true);
  }

  private void setTitle(int menuId) {
    ActionBar actionBar = ((BaseVolleyActivity) getActivity()).getSupportActionBar();
    if (actionBar == null) return;
    switch (menuId) {
      case MY_TODO_LIST:
        actionBar.setTitle(R.string.need_to_do);
        break;
      case MY_DONE_LIST:
        actionBar.setTitle(R.string.already_done);
        break;
      case MY_REQUEST:
        actionBar.setTitle(R.string.my_request);
        break;
      case MY_COMPLETED:
        actionBar.setTitle(R.string.my_finish);
        break;

      default:
        actionBar.setTitle("");
        break;
    }
  }

  @Override public String getUrl() {
    String urlString;
    switch (mMenuId) {
      case MY_TODO_LIST:
        urlString = ApiConst.URL_TASK_LIST;
        break;
      case MY_DONE_LIST:
        urlString = ApiConst.URL_HAS_DONE;
        break;
      case MY_REQUEST:
        urlString = ApiConst.URL_MY_REQUEST;
        break;
      case MY_COMPLETED:
        urlString = ApiConst.URL_MY_COMPLETED;
        break;

      default:
        urlString = ApiConst.URL_TASK_LIST;
        break;
    }
    return urlString;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    if (isRefresh) {
      params.put("curPage", "1");
    } else {
      params.put("curPage", mCurrentPage + "");
    }

    params.put("pageSize", "1000");
    params.put("nodePath", mtypeCode);//流程分类code

    if (mMenuId == MY_TODO_LIST) {
      params.put("applyName", mapplyName);//申请人或部门名
      params.put("Q_beginCreateTime_DL", mBeginTime);//申请开始时间
      params.put("Q_endCreateTime_DG", mEndTime);//申请结束时间
    }

    if (mMenuId == MY_DONE_LIST) {
      params.put("Q_IF_FINISH", mifApproveCode);//是否完成审批code
      params.put("applyName", mapplyName);//申请人或部门名
      params.put("Q_begincreatetime_DL", mBeginTime);//申请开始时间
      params.put("Q_endcreatetime_DG", mEndTime);//申请结束时间
      params.put("Q_subject_SUPL", mtitle);//标题
    }

    if (mMenuId == MY_REQUEST || mMenuId == MY_COMPLETED) {
      params.put("Q_subject_SUPL", mtitle);//标题
      params.put("Q_begincreatetime_DL", mBeginTime);//申请开始时间
      params.put("Q_endcreatetime_DG", mEndTime);//申请结束时间
    }
    return params;
  }

  @Override public void resolveResponse(String arg0) {
    if (isRefresh) {
      mCurrentPage = 2;
    } else {

      mCurrentPage = mCurrentPage + 1;
    }

    TaskList taskList = new Gson().fromJson(arg0, TaskList.class);
    if (tasks == null) {
      tasks = new ArrayList<>();
    }
    tasks.clear();
    if (taskList != null) {
      tasks = taskList.getDataList();
      if (isRefresh) {

        TaskLab.get(getActivity()).removeAll();
      }
      TaskLab.get(getActivity()).addAll(tasks);
      mTasks = TaskLab.get(getActivity()).getTasks();
      if (adapter == null || isRefresh) {
        adapter = new TaskListAdapter(getActivity(), mTasks, mMenuId);
        setListAdapter(adapter);
      } else {

        adapter.addAll(tasks);
      }
      ((TaskListAdapter) getListAdapter()).notifyDataSetChanged();
    } else {

      Toast.makeText(getActivity(), R.string.that_is_all, Toast.LENGTH_SHORT).show();
    }
    getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
      @Override
      public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

        return true;
      }
    });

    getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
      @Override
      public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
        //待办长按item显示checkbox
        if (mMenuId == MY_TODO_LIST) {
          mMenu.getItem(0).setIcon(R.drawable.cancle);
          isBat = true;
          adapter = new TaskListAdapter(getActivity(), mTasks, mMenuId, isBat, i - 1);
          setListAdapter(adapter);
          adapter.notifyDataSetChanged();
          return true;
        } else {
          return false;
        }
      }
    });
  }

  public void onListItemClick(ListView l, View v, int position, long id) {
    Task task = ((TaskListAdapter) getListAdapter()).getItem(position - 1);
    if (task == null) return;
    task.setmMenuId(mMenuId);
    Intent i = new Intent(getActivity(), TaskPagerActivity.class);
    i.putExtra(TaskPagerActivity.EXTRA_TASK_CONTENT, task);
    startActivityForResult(i, 0);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    if (mMenuId == MY_TODO_LIST) {
      inflater.inflate(R.menu.menu_todo_list, menu);
      mMenu = menu;
    } else {
      inflater.inflate(R.menu.menu_query_refresh, menu);
    }
  }

  @TargetApi(11) @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_refresh:
        //			refresh();
        mPullRefreshListView.setMode(Mode.PULL_FROM_START);
        mCurrentPage = 1;
        refresh();
        mPullRefreshListView.setMode(Mode.BOTH);
        return true;
      //批量操作
      case R.id.menu_item_bat:
        if (adapter == null || adapter.getCount() == 0) {
          ToastUtil.show("记录为空无法进行此操作");
        } else {
          if (isBat) {
            isBat = false;
            mMenu.getItem(0).setIcon(R.drawable.bat);
            adapter = new TaskListAdapter(getActivity(), mTasks, mMenuId, false, -1);
          } else {
            isBat = true;
            mMenu.getItem(0).setIcon(R.drawable.cancle);
            adapter = new TaskListAdapter(getActivity(), mTasks, mMenuId, true, -1);
          }
          setListAdapter(adapter);
          ((TaskListAdapter) getListAdapter()).notifyDataSetChanged();
        }
        return true;

      case R.id.menu_item_batAgree:
        //批量操作
        volleyPostMultiple(AGREE);
        return true;

      case R.id.menu_item_batReject:
        //批量操作
        volleyPostMultiple(DISAGREE);
        return true;

      case R.id.menu_item_querys:
        //查询
        ExtraValueContent contet =
            new ExtraValueContent(mtypeName, mtypeCode, mifApproveName, mifApproveCode, mapplyName,
                mtitle, mBeginTime, mEndTime);
        Intent query = new Intent(getActivity(), TodoQueryActivity.class);
        query.putExtra(ToDoQueryFragment.EXTRA_CONTENT, contet);
        query.putExtra(ToDoQueryFragment.EXTRA_FROM, mMenuId);
        startActivityForResult(query, REQUEST_QUERY);
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void volleyPostMultiple(int type) {
    if (adapter != null) {
      StringBuilder bufferTaskIds = new StringBuilder();
      for (int i = adapter.getCount() - 1; i >= 0; i--) {
        Task item = adapter.getItem(i);
        if (item == null) continue;
        String taskId = item.getId();
        if (adapter.isCheckedItem(i)) {
          if (bufferTaskIds.length() > 0) {
            bufferTaskIds.append(",").append(taskId);
          } else {
            bufferTaskIds.append(taskId);
          }
        }
      }
      LogUtil.i("bufferTaskIds===" + bufferTaskIds.toString());
      if (bufferTaskIds.length() == 0) {
        ToastUtil.show(R.string.chooseTodo);
        return;
      }
      String url = "";
      HashMap<String, String> params = new HashMap<>();
      if (AGREE == type) {
        url = ApiConst.getAbsoluteUrl(ApiConst.URL_BAT_AGREE);
        params.put("taskIds", bufferTaskIds.toString());
        params.put("opinion", "同意");
        MyUtils.showDialogLoading(getActivity(), R.string.batComplte);
      } else if (DISAGREE == type) {
        url = ApiConst.getAbsoluteUrl(ApiConst.URL_BAT_DISAGREE);
        params.put("taskIds", bufferTaskIds.toString());
        params.put("opinion", "反对");
        MyUtils.showDialogLoading(getActivity(), R.string.batBack);
      }

      mActivity.volleyPost(url, params, new VolleyResponse() {
        @Override public void onVolleyError(VolleyError arg0) {
        }

        @Override public void onVolleyResponse(String arg0) throws JSONException {
          // 解析响应的字符串
          try {
            SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
            ToastUtil.show(Html.fromHtml(workProcess.getMessage()).toString());
            mPullRefreshListView.setMode(Mode.PULL_FROM_START);
            mCurrentPage = 1;
            refresh();
            mPullRefreshListView.setMode(Mode.BOTH);
          } catch (JsonSyntaxException e) {
            e.printStackTrace();
            ToastUtil.show(R.string.failure_operation);
          }
        }
      });
    }
  }

  private void refresh() {
    isRefresh = true;

    volleyPost();
  }

  @Override public boolean isRefresh() {

    return isRefresh;
  }

  public static TaskListFragment newInstance(int menuId) {
    Bundle args = new Bundle();
    args.putInt(EXTRA_MENU_ID, menuId);
    TaskListFragment fragment = new TaskListFragment();
    fragment.setArguments(args);
    return fragment;
  }

  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {

    Mode mode = refreshView.getCurrentMode();
    if (mode.equals(Mode.PULL_FROM_START)) {
      refresh();
      if (mMenuId == MY_TODO_LIST) {
        //重置菜单
        isBat = false;
        mMenu.getItem(0).setIcon(R.drawable.bat);
      }
    }
    if (mode.equals(Mode.PULL_FROM_END)) {

      isRefresh = false;
      volleyPost();
    }
  }

  @Override public void onDestroy() {
    super.onDestroy();
    TaskLab.get(getActivity()).removeAll();
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;

    if (requestCode == 0) {
      mPullRefreshListView.setMode(Mode.PULL_FROM_START);
      mCurrentPage = 1;
      refresh();
      mPullRefreshListView.setMode(Mode.BOTH);
    }

    if (requestCode == REQUEST_QUERY) {
      //查询
      ExtraValueContent content =
          (ExtraValueContent) data.getSerializableExtra(ToDoQueryFragment.EXTRA_CONTENT);
      mtypeName = content.getExtName1();
      mtypeCode = content.getExtCode1();
      mifApproveName = content.getExtName2();
      mifApproveCode = content.getExtCode2();
      mapplyName = content.getExtName3();
      mtitle = content.getExtName4();
      mBeginTime = content.getExtName5();
      mEndTime = content.getExtName6();

      mPullRefreshListView.setMode(Mode.PULL_FROM_START);
      mCurrentPage = 1;
      refresh();
      mPullRefreshListView.setMode(Mode.BOTH);
    }
  }
}
